package com.my.collection.stack.v10;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Created by ZhongGang
 * at 2018/7/26 15:09
 */
public class MyLock implements Lock {
    private final Sync sync;

    MyLock(int permits) {
        this.sync = new Sync(permits);
    }

    @Override
    public void lock() {
        this.sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        this.sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return this.sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return this.sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        this.sync.release(1);
    }

    @Override
    public Condition newCondition() {
        return this.sync.newCondition();
    }

    private static class Sync extends AbstractQueuedSynchronizer {
        private int permit;

        Sync(int permit) {
            if (permit <= 0) {
                throw new IllegalArgumentException();
            }

            this.permit = permit;
            setState(this.permit);
        }

        @Override
        protected boolean isHeldExclusively() {
            return true;
        }

        @Override
        protected boolean tryAcquire(int arg) {
            int update = this.permit - arg;
            return compareAndSetState(getState(), update) && update > 0;
        }

        @Override
        protected boolean tryRelease(int arg) {
            compareAndSetState(getState(), getState() + arg);
            return true;
        }

        Condition newCondition() {
            return new ConditionObject();
        }
    }

}
